package com.sc.security.controller;


import com.sc.security.model.SysUser;
import com.sc.security.service.UserService;
import com.sc.security.utils.MD5Util;
import com.sc.security.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;


    @RequestMapping("/logout.page")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.removeAttribute("user");
        String path = "signin.jsp";
        response.sendRedirect(path);
    }

    @RequestMapping("/login.page")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String error="";
        String ret = request.getParameter("ret");
        SysUser user =  userService.login(username);
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            error = "用户名或密码不能为空";
        }else if(user==null){
            error="用户不存在";
        }else if(!user.getPassword().equals(MD5Util.encrypt(password))){
            error="用户名或密码错误";
        }else if(user.getStatus()!=1){
            error="用户已被冻结，请联系管理员";
        }else {
         //登录
            request.getSession().setAttribute("user",user);
            if(StringUtils.isNotBlank(ret)){
                response.sendRedirect(ret);
            }else {
                response.sendRedirect("/admin/index.page");
                return;
            }
        }
        request.setAttribute("error",error);
        request.setAttribute("username",username);
        if(StringUtils.isNotBlank(ret)){
            request.setAttribute("ret",ret);
        }
        String path = "signin.jsp";
        request.getRequestDispatcher(path).forward(request,response);
    }
    @RequestMapping("/sys/welcome.page")
    public String welcome(){
        return "index";
    }
}
